<?php
namespace Ntxx\Controller;
use Think\Controller;
class IndexController extends Controller {
    public function index(){
		if(!in_app()){
			$this->display('answer/openapp');
			exit();
		}

		$openID =  $signature = $_GET["oid"];
		session("ntxx_openid",$openID);
		$btnStatus = '';
		$startTime = "2018-01-21  00:00:00";
		$finishTime = "2018-01-30 23:59:59";
		if(strtotime ( $startTime ) > time ()) {
			$btnStatus = "disabled";
		}
		elseif(strtotime ( $finishTime ) < time ()){
			$btnStatus = "disabled";
		}

		$this->assign("OnTime",$btnStatus);
        $this->display();
	}
	
	public function study(){
		$this->display();
	}

	public function wechatVerify()
	{
		if (IS_POST) {
			$appid = C('WECHAT_APPID');//'wx3f2b6fb3bcec1e9f'; //AppID(应用ID)
			$token = C('WECHAT_TOKEN');//'R9LDv7WGVCqMx2gl7fzQEd2u979E9F8e'; //微信后台填写的TOKEN
			$crypt = C('WECHAT_APPSECRET');//'J9cgDLcg59ZGlENg76977Gnew5887EFzLnV9l89uX5E'; //消息加密KEY（EncodingAESKey）
			try {
				$wechat = new Wechat($token, $appid, $crypt);
				/* 获取请求信息 */
				$data = $wechat->request();

				if ($data && is_array($data)) {
					$this->doWithWeChatMsg($wechat, $data);
				}
			}catch(\Exception $e){
				dump($e->getMessage());
			}

		} else {
			$echoStr = $_GET["echostr"];
//            dump($echoStr);
			if ($this->checkSignature()) {
				echo $echoStr;
				exit;
			}
		}
	}

	private function doWithWeChatMsg($wechat, $data){
		if($data['MsgType']=='text' && $data['Content'] == '答题'){
			$wechat->replyText("请点击链接答题："."http://game.jjcbw.com/ntxx/?oid=".$data['FromUserName']);
		}
	}

	private function checkSignature()
	{
		$signature = $_GET["signature"];
		$timestamp = $_GET["timestamp"];
		$nonce = $_GET["nonce"];

		$token = C('WECHAT_TOKEN');//'R9LDv7WGVCqMx2gl7fzQEd2u979E9F8e';
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );

		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}